#include <compilation/Table.h>
#include <compilation/instruction/InstructionVisitor.h>

#include <sstream>


namespace compilation
{


Scope::FindResult
Scope::find(const std::string& name, int& local, Scope& scope) const
{
  FindResult result = FRNotFound;
  std::shared_ptr<SymbolTable> current = m_last;
  while (current.get() && result == FRNotFound)
  {
    if (current->contain(name))
    {
      local = current->localIndex(name);
      if (current->m_parent.get())
      {
        result = FRLocal;
        scope = Scope(current);
      }
      else result = FRGlobal;
    }
    current = current->m_parent;
  }
  return result;
}


int
Scope::getFunctionIndex(int local) const
{
  std::shared_ptr<SymbolTable> current = m_last;
  while (current->m_parent.get())
  {
    local += current->m_parent->m_localIndexes.size();
    current = current->m_parent;
  }
  return local;
}


} // compilation
